package com.chaihu.jpaDemo.modules.common.controller;

import com.chaihu.jpa.service.BaseService;
import com.chaihu.jpaDemo.modules.common.dto.ResultObject;
import com.chaihu.jpaDemo.modules.common.entity.BaseEntity;
import com.chaihu.jpaDemo.utils.BeanUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;


/**
 * 简单对象curd,不配置权限
 * Create By qinzhw
 * 2018年5月8日上午9:14:24
 */
@RestController
public abstract class CrudController<E extends BaseEntity, ID extends Serializable> extends BaseController {

    protected abstract BaseService<E, ID> getService();

    /*******************Restful  crud *********************/
    @GetMapping("{id}")
    @ApiOperation(value = "查看", notes = "根据ID查询")
    @ApiImplicitParam(name = "id", value = "表ID", required = true, dataType = "Long", paramType = "path")
    public ResultObject<E> findById(@PathVariable ID id) {
        return ResultObject.ok(getService().findOne(id));
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "删除", notes = "根据ID删除")
    @ApiImplicitParam(name = "id", value = "表ID", required = true, dataType = "Long", paramType = "path")
    public ResultObject<?> deleteById(@PathVariable ID id) {
        E e1 = getService().findOne(id);
        if (e1 == null) {
            return ResultObject.ok("对象不存在");
        }
        getService().deleteById(id);
        return ResultObject.ok("删除成功");

    }

    @PostMapping
    @ApiOperation(value = "新增", notes = "新增方法")
    public ResultObject<?> add(@Valid @RequestBody E entity, BindingResult br) {
        if (br.hasErrors()){
            return ResultObject.error(getValidErrorMsg(br));
        }
        E e = getService().save(entity);
        if (e != null) {
            return ResultObject.ok(e,"新增成功");
        }
        return ResultObject.error("新增失败");
    }

    @PutMapping
    @ApiOperation(value = "修改", notes = "修改方法")
    public ResultObject<?> modify(@RequestBody E entity) {
        E target = getService().findOne((ID) entity.getId());
        if (target == null) {
            return ResultObject.error("对象不存在");
        }
        BeanUtil.copyPropertiesIgnoreNull(entity,target);
        E e = getService().save(target);
        if (e != null) {
            return ResultObject.ok(e,"更新成功");
        }
        return ResultObject.error("更新失败");
    }

    /*******************Restful crud*********************/

}
